from django.shortcuts import render, HttpResponse

# Create your views here.
from django.views import View
from .models import *
import json


class ShowBooksView(View):
    def get(self, request):
        bookslist = Books.objects.filter().all()
        booksdata = []
        for i in bookslist:
            booksdata.append({
                'id': i.id,
                'bookname': i.bookname,
                'price': str(i.price),
                'author': i.author_id
            })
        authorslist = Author.objects.filter().all()
        authorsdata = []
        for i in authorslist:
            authorsdata.append({
                'id': i.id,
                'authorname': i.name,
            })
        return HttpResponse(json.dumps({'code': 200, 'booksdata': booksdata, 'authorsdata': authorsdata}))


class AuthorView(View):
    def get(self, request):
        authorslist = Author.objects.filter().all()
        authorsdata = []
        for i in authorslist:
            authorsdata.append({
                'id': i.id,
                'authorname': i.name,
            })
        return HttpResponse(json.dumps({'code': 200, 'data': authorsdata}))


class Addbooks(View):
    def post(self, request):
        bookname = request.POST.get('bookname')
        price = request.POST.get('price')
        author = request.POST.get('author')
        Books.objects.create(bookname=bookname, price=int(price), author_id=int(author))
        return HttpResponse(json.dumps({'code': 200}))


class Delbooks(View):
    def get(self, request, *args, **kwargs):
        cc = args[0]
        Books.objects.filter(id=cc).delete()
        return HttpResponse(json.dumps({'code': 200}))


class Updbooks(View):
    def get(self, request, *args, **kwargs):
        cc = args[0]
        book = Books.objects.filter(id=cc).first()
        bookdata = {'bookname': book.bookname, 'price': str(book.price)}
        return HttpResponse(json.dumps({'code': 200, 'data': bookdata}))


class Updbooks1(View):
    def post(self, request):
        cc = request.POST.get('id')
        bn = request.POST.get('bookname')
        pe = request.POST.get('price')
        Books.objects.filter(id=int(cc)).update(bookname=bn, price=pe)
        return HttpResponse(json.dumps({'code': 200}))
